import java.io.*;
import java.util.*;
public class PriceAnalyzer {
    public static void main(String[] args) {
        String fileName = "D:/PriceAnalyzer.txt";
        File file = new File(fileName);
        List<Integer> prices = new ArrayList<>();
        Scanner sc = null;
        try {
            sc = new Scanner(file);
            sc.useDelimiter("[^0123456789]+");
            while (sc.hasNext()) {
                String line = sc.nextLine();
                line = line.trim();
                if (line.isEmpty() || line.startsWith("商品列表:")) {
                    continue;
                }
                String[] parts = line.split("，");
                if (parts.length >= 2) {
                    String priceStr = parts[1].replace("元/台", "").trim();
                    int price = Integer.parseInt(priceStr.replaceAll("\\s+", ""));
                    prices.add(price);
                }
            }
            if (prices.size() > 0) {
                double averagePrice = prices.stream().mapToInt(Integer::intValue).average().orElse(0);
                String moreaveragePrice = String.format("%.3f",averagePrice);
                try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true))) {
                    bw.newLine();
                    bw.write("平均价格：" + moreaveragePrice + "元/台");
                }
            } else {
                System.out.println("没有读取到任何有效价格信息。");
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            if (sc!= null) {
                sc.close();
            }
        }
        if (!file.exists()) {
            System.out.println("文件 '" + fileName + "' 不存在。");
        }
    }
}
